﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lapkin.Helpers;
using Lapkin.Models.ViewModel;
using WebMatrix.WebData;

namespace Lapkin.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        [AllowAnonymous]
        public ActionResult Index()
        {
            return RedirectToAction("Login");
        }

        [AllowAnonymous, HttpGet]
        public ActionResult Login()
        {
            return WebSecurity.IsAuthenticated ? (ActionResult) RedirectToAction("Logout") : View(new LoginModel());
        }

        [AllowAnonymous, HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel loginModel)
        {
            if (ModelState.IsValid)
            {
                if (WebSecurity.Login(loginModel.Email, loginModel.Password.GetShaHash(), loginModel.RemeberMe))
                {
                    var returnUrl = Request.QueryString["ReturnUrl"];
                    return returnUrl != null ? (ActionResult) Redirect(returnUrl) : RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("ErrorAuth", "Почта или пароль не верны." );
            }
            return View(loginModel);
        }

        [HttpGet]
        public ActionResult Logout()
        {
            WebSecurity.Logout();
            return RedirectToAction("Index", "Home");
        }

    }
}
